﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime;

namespace XYZCompiler
{
    class CompilePartFactory
    {
        public CompilePartFactory()
        {
            Inti();
        }

        void Inti()
        {
            _partInfo.Add(FlowController.CompileState.READY.ToString(), "XYZCompiler.LexerPart");
            _partInfo.Add(FlowController.CompileState.LEXER_COMPLETED.ToString(), "XYZCompiler.ParserPart");
            _partInfo.Add(FlowController.CompileState.SYNTACTIC_COMPLETED.ToString(), "XYZCompiler.SemanticPart");
        }

        public CompilePartBase this[FlowController.CompileState CurrentState]
        {
            get
            {
                //return new LexerPart();
                if (_cache.ContainsKey(CurrentState))
                {
                    return _cache[CurrentState];
                }
                else
                {
                    var t = Type.GetType(_partInfo[CurrentState.ToString()]);
                    var instance = System.Activator.CreateInstance(t) as CompilePartBase;
                    if(instance == null)
                        throw  new Exception("Create Part failed ! Part name:"+CurrentState.ToString());
                    _cache[CurrentState] = instance;
                    return instance;
                }
            }
        }

        private readonly Dictionary<string,string> _partInfo = new Dictionary<string, string>(); 

        private readonly Dictionary<FlowController.CompileState,CompilePartBase> _cache = new Dictionary<FlowController.CompileState, CompilePartBase>();
    }
}
